package com.example.mvvm.mvc.login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.mvvm.R;

public class MainActivity extends AppCompatActivity implements LoginModel.OnDoLoginStateChange {
    private EditText account,password;
    private Button loginBtn;
    private TextView loginPrompt;
    LoginListener loginListener;

    LoginModel loginModel = new LoginModel();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

        setListeners();
    }

    private void setListeners() {
        loginListener = new LoginListener();
        loginBtn.setOnClickListener(loginListener);
    }

    private void findViews() {
        password = findViewById(R.id.password);
        account = findViewById(R.id.account);
        loginBtn = findViewById(R.id.login);
        loginPrompt = findViewById(R.id.login_prompt);
    }

    @Override
    public void onLoginSuccess() {
        loginPrompt.setText("登录成功");
    }

    @Override
    public void onLoginFailed() {
        loginPrompt.setText("登录失败");
    }

    @Override
    public void onLoginLoading() {
        loginPrompt.setText("登录中...");
    }

    class LoginListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.login:
                    //进行登录
                    toLogin();
                    break;
            }
        }
    }

    /**
     * 做登录的逻辑处理
     */
    private void toLogin() {
        String accountStr = account.getText().toString();
        String passwordStr = password.getText().toString();
        //检查账号格式是否正确
        if(TextUtils.isEmpty(accountStr)){
            //todo 提示账号有问题
            return;
        }
        //检查密码长度是否正确
        if(TextUtils.isEmpty(passwordStr)){
            //todo 提示密码有问题
            return;
        }
        //密码加盐
        //passwordStr = MD5Utils.md5(passwordStr);
        int block = loginModel.checkUsername(accountStr);
        if(block == 0){
           //没注册
        } else if(block == 1){
            //注册过
            //进行登录,此操作为异步
            loginModel.doLogin(this,accountStr,passwordStr);
            //禁止按钮可以点击，防止重复提交
            loginBtn.setEnabled(false);
        }

    }
}